import Common
from M3u8ReaderUtil import M3u8Reader

class PutHandler:
    
    def resolve(self, user, name):
        if Common.strContains(name, ".ts"):
            self.PUT_ts(user, name)
        elif Common.strContains(name, ".m3u8") or Common.strContains(name, ".jpg"):
            self.PUT_m3u8(user, name)
            
        Common.writeToOutput(Common.MSG0LEN)
            
    def PUT_ts(self, user, name):
        Common.putLogger.logthis("PUT TS: " + name + " at " + str(Common.timepkg.time()), Common.Logger.PUT_Request)
        Common.writeStdinToFile(name, "wb")
        
    def PUT_m3u8(self, user, name):
        names = Common.globpkg.glob("%s-*" % name)
        name = "%s-%d-%d" % (name, Common.GetCurrentTime(), Common.GetRandInt(100000,999999))
        Common.putLogger.logthis("PUT M3u8: " + name, Common.Logger.PUT_Request)
        Common.writeStdinToFile(name, "wb")
        
        #remove older name-m3u8.* if they are older than TIMEOUT
        minThreshold = Common.GetModifyTime(name) - 30    #min threshold
        while len(names) > 2:       # more than one timestamps for name.m3u8 exists
            (accessTime, filename) = min((Common.GetModifyTime(filename), filename) for filename in names)
            if accessTime > minThreshold:
                break       # ignore m3u8 generated within the last PUT_REMOVE_TIMEOUT
                            # do not consider other files, since the minimum is selected and if that is within the threshold, all the others will already be within the threshold
            #otherwise try to remove it if it has not been removed already
#            Common.putLogger.logthis("Trying to remove " + filename, Common.Logger.PUT_Request)
            Common.DeleteFile(filename)
            names.remove(filename)
            
#        tempM3u8 = str(Common.GetCurrentTime()) + "_tempm3u8.m3u8"
#        Common.writeStdinToFile(tempM3u8, "wb")
#        m3u8 = M3u8Reader(tempM3u8).getM3u8()
#        firstTs = m3u8.GetFirstTS()
#        seqNum = Common.SequenceNumber(firstTs)
#        name = "%s-%d-%d" % (name, Common.GetCurrentTime(), seqNum)
#        Common.Rename(tempM3u8, name)
##        Common.DeleteFile(tempM3u8)
#        Common.writeStdinToFile(name, "wb")